package com.ksyun.campus.dataserver.services;

import com.alibaba.fastjson.JSONObject;
import com.ksyun.campus.dataserver.config.dataserverconfig.DataServerConfigProperties;
import com.ksyun.campus.dataserver.domain.DataServerInfo;
import com.ksyun.campus.dataserver.domain.ReplicaData;
import com.ksyun.campus.dataserver.util.MyZkSerializer;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Component
@Slf4j
public class HeartBeatService {
    @Resource
    private ZkClient zkClient;
    @Resource
    DataServerConfigProperties dataServerConfigProperties;

    @Resource
    private DataServerInfo dataServerInfo;

    @Resource
    private Map<String, ReplicaData> replicaDataMap;

    @Scheduled(cron = "0/3 * * * * ?")
    public void heartBeat() {
        // 同步dataServer信息到zookeeper节点 记录信息
        dataServerInfo.setRack(dataServerConfigProperties.getRack());
        dataServerInfo.setZone(dataServerConfigProperties.getZone());
        dataServerInfo.setAllReplicaDataMap(replicaDataMap);
        // 解决zk写入数据乱码
        zkClient.setZkSerializer(new MyZkSerializer());
        if (zkClient.exists(dataServerConfigProperties.getFullNode())){
            zkClient.writeData(dataServerConfigProperties.getFullNode(), JSONObject.toJSONString(dataServerInfo));
        }
    }



}
